<template>
  <div class="container">
    <van-sticky>
      <div class="head">
        <img class="head-back-img" @click="goBack" src="../assets/back.svg" alt="">
        <div class="title">订单详情</div>
      </div>
    </van-sticky>
    <header>
      <div>{{ detailObj.status }}</div>
      <!--      -->
      <div v-if="detailObj.status === '待支付'" class="notic">请尽快完成付款，剩<van-count-down format="mm 分 ss 秒"
          :time="checkTimeWithin10Minutes(detailObj.createTime)" />自动关闭</div>
      <div>
        <div v-if="detailObj.status === '出票成功'" @click="getCode">取票</div>
        <!-- <div v-if="detailObj.status === '待支付'" @click="gopay">去支付</div> -->
        <!-- <div v-if="detailObj.isRefund === 1">申请退款</div> -->
      </div>
    </header>
    <div class="card-cin">
      <div>
        <div>
          <span>{{ detailObj.cinemaName }}</span>
          <!-- <img src="../assets/mine/goShift.svg" alt=""> -->
        </div>
        <div></div>
      </div>
      <div>
        <div class="left">
          <div>{{ detailObj.filmName }}</div>
          <div>
            <span>{{ detailObj.versionType }}</span>
            <span style="margin-left: 5px">{{ detailObj.ticketNum }}张</span>
          </div>
          <div>
            <div v-if="detailObj.showTime">{{ formatDateTime(detailObj.showTime, 'day') }}</div>
            <div>{{ detailObj.hallName }}</div>
          </div>
          <div>
            <div v-if="detailObj.showTime">{{ formatDateTime(detailObj.showTime, 'time') }}</div>
            <div>{{ copynewSeatName }}</div>
          </div>
        </div>
        <div class="right">
          <img :src="$buildFullImageUrl + detailObj.pic" alt="">
        </div>
      </div>
    </div>
    <div class="order-detail">
      <div>
        <span>订单详情</span>
        <!-- <div>
          <span>结算明细</span>
          <img src="../assets/mine/goShift.svg" alt="">
        </div> -->
      </div>
      <div class="line">
        <div>消费金额：</div>
        <div>¥ {{ detailObj.clientMarketAmount ? detailObj.clientMarketAmount : 0 }}</div>
      </div>
      <div class="line">
        <div>订单编号：</div>
        <div>{{ detailObj.orderNo }}</div>
      </div>
      <div class="line">
        <div>购买时间：</div>
        <div>{{ detailObj.createTime }}</div>
      </div>
      <div v-if="detailObj.status === '出票成功'" class="line">
        <div>出票时间：</div>
        <div>{{ detailObj.ticketTime }}</div>
      </div>
      <div class="line">
        <div>手机号码：</div>
        <div v-if="detailObj.phone">{{ hidePhoneMiddle(detailObj.phone) }}</div>
      </div>
    </div>
    <div class="detail-five">
      <div>观影须知</div>
      <div class="con">1、请按纸质票/电子票载明的日期及场次观看，当日当场首次进场有效。一人一票，对号入座，个别场次须凭有效身份证件原件，票证一致方可入场。</div>
      <div class="con">2、具体入场时间以场馆规定为准,建议您视活动规 模,提前60-120分钟检票入场。若您迟到,请向现场 工作人员寻求帮助,并在工作人员安排下入场,请勿
        擅自入场或扰乱市场秩序;部分项目针对依主办方或
        场馆要求个别活动的特殊性,迟到可能无法入场,请 以现场工作人员的要求为准。</div>
      <div class="con">3、建议您着装整洁,服从现场工作人员安排,遵守 秩序,依序入场,并请自觉接受安全检查。严禁携带枪支、弹药、管制刀具等违禁物品;严禁携带打火机 等易燃易爆物品;严禁携带液态物品;其它根据个别
        活动要求严禁携带入场的物品。</div>
      <!--      <div class="btn">在线客服</div>-->
    </div>
    <van-overlay :show="show" @click="show = false">
      <div class="wrapper">
        <div class="block">
          <div>
            <span>取票核销码</span>
            <img @click="show = false" src="../assets/order/close.svg" alt="二维码" />
          </div>
          <div>{{ detailObj.ticketContentTips }}</div>
          <div>
            <div v-for="(image, index) in codeList" :key="index" class="qr-item">
              <img v-if="image.imgUrl" :src="image.imgUrl" alt="取票码二维码" />
              <!--              <div class="seat-info">{{ image.text }}</div>-->
              <!-- <div class="seat-info">
                <div v-for="x of newSeatName">{{ x }}</div>
              </div> -->
              <!-- <div v-if="detailObj.ticketContent" class="verification-code">
                取票码: {{ detailObj.ticketContent }}
              </div> -->
            </div>

          </div>
             <div class="verification-code">
            <div>
              取票码: {{ detailObj.ticketContent }}
            </div>
            <!-- <div>
              验证码: {{ verificationCodes }}
            </div> -->
          </div>
        </div>
      </div>
    </van-overlay>
  </div>
</template>
<script>
import plantAPI from "@/api/plant";
import QRCode from "qrcode";

export default {
  data() {
    return {
      active: 1,
      show: false,
      order_no: '',
      detailObj: {},
      qrImageUrl: "",
      codeList: [],
      newSeatName: [],
      copynewSeatName:[]
    }
  },
  created() {

    this.order_no = this.$route.query.orderNo;
    plantAPI.getunorderAPI(this.order_no).then(res => {
      this.detailObj = res.data;
      this.newSeatName = this.detailObj.seatNames.replace(/\|/g, '  ');
      this.copynewSeatName = this.detailObj.seatNames.replace(/\|/g, '  ');
      if (this.detailObj) {
        // 同时传入票码内容和座位信息
        this.codeList = this.parseTicketCodes(
          this.detailObj.ticketContent,
          this.detailObj.seatNames
        );
      }
    });

  },
  methods: {
    parseTicketCodes(input, seats) {
      console.log(input,'input')
      if (!input || typeof input !== 'string') return [];
      const trimmedInput = input.trim();
      if (!trimmedInput) return [];

      // 分割座位信息
      const seatArray = seats ? seats.split(/[,，]/).map(s => s.trim()) : [];

      const codeSegments = trimmedInput.split(/[,，]/).map(s => s.trim()).filter(Boolean);
      return codeSegments.map((segment, index) => {
        const separator = segment.includes('|') ? '|' : (segment.includes('｜') ? '｜' : null);
        const seatText = seatArray[index] || '';

        if (separator) {
          const [ticketCode, verificationCode] = segment.split(separator);
          return {
            ticketCode: ticketCode.trim(),
            verificationCode: verificationCode.trim() || null,
            text: seatText  // 添加座位信息
          };
        }

        return {
          ticketCode: segment,
          verificationCode: null,
          text: seatText  // 添加座位信息
        };
      });
    },
    async getCode() {
      this.show = true;
      if (this.codeList.some(item => item.imgUrl)) return;
      this.newSeatName = this.detailObj.seatNames.split('|').map(item => item.trim());
      const newCodeList = [...this.codeList];
      for (let item of newCodeList) {
        try {
          item.imgUrl = await this.generateQRCode(
            item.ticketCode
          );
        } catch (e) {
          item.imgUrl = '';
        }
      }
      console.log(newCodeList)
      this.codeList = newCodeList;
    },
    async generateQRCode(qrData) {
      try {
        // 生成二维码并转换为 Data URL
        const qrImageUrl = await QRCode.toDataURL(qrData, {
          width: 200,          // 宽度
          margin: 2,           // 边距
          errorCorrectionLevel: "H",
        });
        return qrImageUrl
      } catch (err) {
      }
    },

    gopay() {

    },
    goBack() {
      const fromRoute = this.$route.from; // 获取来源路由
      if (fromRoute && fromRoute.path == '/my-order') {
        this.$router.push('/my-order');
      } else {
         this.$router.push({
          path: '/home'
        })
      }
    },
    checkTimeWithin10Minutes(targetTimeStr) {
      // 1. 将目标时间字符串转换为 Date 对象
      const targetTime = new Date(targetTimeStr);

      // 2. 计算目标时间 + 10 分钟后的时间
      const targetTimePlus10Min = new Date(targetTime.getTime() + 10 * 60 * 1000);

      // 3. 获取当前时间
      const now = new Date();
      // 4. 判断是否超过 10 分钟
      if (now > targetTimePlus10Min) {
        return 0; // 超过 10 分钟
      } else {
        return targetTimePlus10Min - now; // 返回剩余毫秒数
      }
    },
    hidePhoneMiddle(phone) {
      return phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
    },
    formatDateTime(inputDateTime, key) {
      const now = new Date();
      const inputDate = new Date(inputDateTime);

      // 提取年、月、日
      const inputYear = inputDate.getFullYear();
      const inputMonth = String(inputDate.getMonth() + 1).padStart(2, '0');
      const inputDay = String(inputDate.getDate()).padStart(2, '0');

      const currentYear = now.getFullYear();
      const currentMonth = String(now.getMonth() + 1).padStart(2, '0');
      const currentDay = String(now.getDate()).padStart(2, '0');

      // 处理日期部分
      let dateStr;
      if (inputYear === currentYear && inputMonth === currentMonth && inputDay === currentDay) {
        dateStr = `今天 ${inputMonth}-${inputDay}`;
      } else if (inputYear === currentYear) {
        dateStr = `${inputMonth}-${inputDay}`;
      } else {
        dateStr = `${inputYear}-${inputMonth}-${inputDay}`;
      }

      // 处理时间部分（截取 "18:50:00" → "18:50"）
      const timeStr = inputDateTime.split(' ')[1].substring(0, 5);

      // return [dateStr, timeStr];
      if (key === 'day') {
        return dateStr
      } else if (key === 'time') {
        return timeStr
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.container {
  min-height: 100vh;
  padding-bottom: 10px;
  //box-sizing: border-box;
  /* 确保容器撑满整个视口 */
  //background: linear-gradient(94deg, rgba(238, 71, 59, 0.05) 0%, #f6766d 58%, rgba(238, 71, 59, 0.3) 100%);
  background: linear-gradient(to bottom, rgba(238, 71, 59, .4) 20%, rgb(244, 244, 244) 80%);

  ::v-deep .van-sticky {
    background: #ffffff;

  }

  .head {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    position: relative; // 关键：设置相对定位
    background-color: #ffffff;

    .head-back-img {
      width: 20px;
      height: 20px;
      position: absolute;
      left: 15px;
    }

    .title {
      width: 100%;
      text-align: center;
      font-size: 16px;
      color: #000000;
    }
  }

  header {
    width: 100%;
    padding: 10px 20px;
    box-sizing: border-box;

    >div:nth-child(1) {
      width: 100%;
      text-align: center;
      font-size: 16px;
      color: #ffffff;
    }

    .notic {
      width: 100%;
      height: 30px;
      line-height: 30px;
      text-align: center;
      font-size: 12px;
      color: #fdf9f9;
      display: flex;
      align-items: center;
      justify-content: center;

      .van-count-down {
        color: #fdf9f9;
        font-size: 12px;
        margin: 0 2px;
      }
    }

    >div:last-child {
      width: 100%;
      display: flex;
      justify-content: center;
      margin-top: 10px;
      gap: 15px;

      >div {
        width: 100px;
        height: 30px;
        line-height: 30px;
        border: 1px solid #ffffff;
        text-align: center;
        font-size: 12px;
        color: #ffffff;
        border-radius: 20px;
      }
    }
  }

  .card-cin {
    width: calc(100% - 20px);
    margin: auto;
    background-color: #ffffff;
    border-radius: 10px;
    overflow: hidden;

    >div:nth-child(1) {
      width: 100%;
      height: 40px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 10px;
      box-sizing: border-box;
      background: rgb(250, 249, 254);

      >div:nth-child(1) {
        font-size: 14px;
        color: #5B626A;
        display: flex;
        align-items: center;

        span {
          display: inline-block;
        }

        img {
          width: 10px;
          height: 10px;
          margin-top: 2px;
          margin-left: 5px;
        }
      }
    }

    >div:nth-child(2) {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px 10px;
      box-sizing: border-box;

      .left {
        width: calc(100% - 88px);
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;

        >div:nth-child(1) {
          width: 100%;
          text-overflow: ellipsis;
          white-space: nowrap;
          overflow: hidden;
          font-size: 14px;
          color: #1e1d1e;
        }

        >div:nth-child(2) {
          width: 100%;
          margin-top: 3px;
          font-size: 12px;
          text-overflow: ellipsis;
          white-space: nowrap;
          overflow: hidden;
          color: #656365;
        }

        >div:nth-child(3) {
          width: 100%;
          margin-top: 10px;
          font-size: 12px;
          color: #656365;
          display: flex;
          align-items: center;
          justify-content: space-between;
          line-height: 15px;

          >div:nth-child(1) {
            width: 40%;
          }

          >div:nth-child(2) {
            width: 60%;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
          }
        }

        >div:nth-child(4) {
          width: 100%;
          margin-top: 3px;
          font-size: 12px;
          color: #1e1d1e;
          display: flex;
          //align-items: center;
          justify-content: space-between;
          line-height: 15px;

          >div:nth-child(1) {
            width: 40%;
          }

          >div:nth-child(2) {
            width: 60%;
          }
        }
      }

      .right {
        width: 78px;
        height: 105px;
        border-radius: 5px;

        img {
          width: 100%;
          height: 100%;
          border-radius: 5px;
        }
      }
    }
  }

  .order-detail {
    width: calc(100% - 20px);
    margin: 10px auto;
    background-color: #ffffff;
    border-radius: 10px;
    overflow: hidden;

    >div:nth-child(1) {
      width: 100%;
      height: 40px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 10px;
      box-sizing: border-box;

      >span:first-child {
        font-size: 14px;
        color: #000;
      }

      >div:nth-child(2) {
        font-size: 12px;
        color: #5B626A;
        display: flex;
        align-items: center;

        span {
          display: inline-block;
        }

        img {
          width: 10px;
          height: 10px;
          margin-top: 2px;
          margin-left: 5px;
        }
      }

    }

    .line {
      width: 100%;
      font-size: 12px;
      display: flex;
      align-items: center;
      padding: 0 10px;
      box-sizing: border-box;
      margin-bottom: 10px;
      color: #656365;

      >div:nth-child(1) {
        width: 60px;
        height: 15px;
        line-height: 15px;

      }

      >div:nth-child(2) {
        width: calc(100% - 60px);
        height: 15px;
        line-height: 15px;
        color: #414040;

      }
    }
  }

  .detail-five {
    width: calc(100% - 20px);
    margin: 10px auto 0;
    background-color: #ffffff;
    border-radius: 10px;
    overflow: hidden;

    >div {
      width: 100%;
    }

    >div:first-child {
      font-size: 14px;
      color: #000;
      width: 100%;
      height: 40px;
      line-height: 40px;
      padding: 0 10px;
      box-sizing: border-box;
    }

    .con {
      width: 100%;
      color: #656365;
      font-size: 12px;
      padding: 0 10px;
      box-sizing: border-box;
      margin-bottom: 5px;
    }

  }

  .wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .block {
    width: 300px;
    //height: 300px;
    background-color: #fff;
    border-radius: 15px;
    padding: 7px 13px;
    box-sizing: border-box;

    >div:nth-child(1) {
      color: rgba(16, 16, 16, 1);
      font-size: 18px;
      font-weight: bold;
      width: 100%;
      display: flex;
      justify-content: space-between;

      img {
        width: 22px;
        height: 29px;
      }

    }

    >div:nth-child(2) {
      color: rgba(154, 154, 154, 1);
      font-size: 14px;
      margin-top: 5px;
      width: 100%;
      text-align: left;
    }

    >div:nth-child(3) {
      width: 143px;
      //height: 180px;
      margin: 25px auto 0;

      .van-swipe {
        width: 150px;
        height: 170px;
        margin: auto;
      }

      .van-swipe-item {
        display: flex;
        flex-wrap: wrap;

        img {
          width: 150px;
          height: 150px;
        }

        >div {
          width: 100%;
          height: 20px;
          line-height: 20px;
          font-size: 14px;
          font-weight: bold;
          text-align: center;
        }
      }

      //img {
      //  width: 143px;
      //  height: 155px;
      //}
    }
  }
}

.qr-item {
  text-align: center;

  img {
    width: 150px;
    height: 150px;
    display: block;
    margin: 0 auto;
  }

  .seat-info {
    margin-top: 5px;
    font-size: 14px;
    font-weight: bold;
    color: #333;
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    >div {
      flex: 0 0 calc(50% - 5px);
      //margin: 5px 0;
    }
  }

  .seat-info:only-child {
    justify-content: center;
  }

}
.verification-code {
  margin-top: 15px;
  padding: 10px;
  font-size: 14px;
  color: #000;
  background: #ccc;
  width: calc(100% - 20px);
  margin:10px auto;
  >div:first-child {
   margin-bottom: 5px;
  }
}
</style>
